package com.kqzz.common.config.log.mdc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.kqzz.common.utils.SystemContants;

/**
 * @Description 日志全链路追踪拦截器
 * @ClassName LogInterceptor.java
 * @Package com.kqzz.oauth2.config.log.mdc 
 * @author lipeng
 * @date 2022年1月11日 下午4:01:04
 * 
 * @update_Desc
 * @update_Author
 * @update_Date
 */
public class LogInterceptor implements HandlerInterceptor {
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//		System.out.println("LogInterceptor:"+request.getRequestURI());
        //如果有上层调用就用上层的ID
        String traceId = request.getHeader(SystemContants.TRACE_ID);
        if (traceId == null) {
            traceId = TraceIdUtil.genTraceId();
        }
        MDC.put(SystemContants.TRACE_ID, traceId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        //调用结束后删除
        MDC.remove(SystemContants.TRACE_ID);
    }
}
